package de.stefanocke.roo.xtend

import org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetailsBuilder
import org.springframework.roo.classpath.details.FieldMetadataBuilder
import org.springframework.roo.classpath.details.MethodMetadata
import org.springframework.roo.classpath.layers.MemberTypeAdditions
import org.springframework.roo.classpath.layers.MethodParameter
import org.springframework.roo.model.JavaType

import static org.springframework.roo.classpath.details.ImportMetadataBuilder.*

import static extension de.stefanocke.roo.xtend.Annotation.*
import static extension de.stefanocke.roo.xtend.Counter.*
import static extension de.stefanocke.roo.xtend.RooExtensions.*

class MemberTypeAdditionsHelper {
	def static MemberTypeAdditions createMemberTypeAdditions(String callerMid, JavaType target, 
		MethodMetadata methodMetadata, JavaType injectAnnotation
	) {

		val builder = new ClassOrInterfaceTypeDetailsBuilder(callerMid)
		val methodName = methodMetadata.methodName.symbolName;
		
//		int paramSize = methodMetadata.getParameterNames().size();
//		List<MethodParameter> methodParameters = new ArrayList<MethodParameter>(paramSize);
//		for (int i = 0; i < paramSize; i++) {
//			methodParameters.add(new MethodParameter(methodMetadata.getParameterTypes().get(i).getJavaType(), methodMetadata
//					.getParameterNames().get(i)));
//		}
//		
		val methodParameters = methodMetadata.parameterNames.counter.map ( 
			i |	new MethodParameter(methodMetadata.parameterTypes.get(i).javaType, methodMetadata.parameterNames.get(i))
		).toList
		
		val isStatic = methodMetadata.isStatic
		val targetName = 
				if(isStatic){		
					builder.add(getImport(callerMid, target));
					target.getSimpleTypeName();
				} else {

					val name = target.simpleTypeName.toFirstLower
					builder.addField(new FieldMetadataBuilder(callerMid, 0, newArrayList(injectAnnotation.annotation), name.symbol, target));
					name
				}
		return MemberTypeAdditions::getInstance(builder, targetName, methodName, isStatic, methodParameters);
	}
}